package life.system.order.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import life.system.order.vo.OrderDetailVo;
import life.system.order.vo.OrderListVo;
import life.system.order.vo.OrderSubmitVo;
import life.system.order.vo.SubmitOrderResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import life.system.order.entity.OrderEntity;
import life.system.order.service.OrderService;
import life.system.common.utils.PageUtils;
import life.system.common.utils.R;



@RestController
@RequestMapping("order/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = orderService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
		OrderEntity order = orderService.getById(id);

        return R.ok().put("order", order);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody OrderEntity order){
		orderService.save(order);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody OrderEntity order){
		orderService.updateById(order);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
		orderService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }


    @PostMapping("/app/submitOrder")
    public R submitOrder(@RequestBody OrderSubmitVo submitVo) {
        // 下单 去创建订单
        try {
            SubmitOrderResponseVo responseVo = orderService.submitOrder(submitVo);
            if (responseVo.getCode() == 0) {
                return R.ok().put("data", responseVo);
            } else {
                // 订单失败 返回到订单确认页面
                String msg = "下订单失败,";
                switch (responseVo.getCode()) {
                    case 1:
                        msg += "订单信息过期，请刷新后再次提交。";
                        break;
                    case 2:
                        msg += "订单中的商品价格发生变化，请刷新后再次提交。";
                        break;
                }
                return R.error(msg);
            }
        } catch (Exception e) {
            return R.error("下单失败");
        }
    }


    @GetMapping("/app/{orderSn}/detail")
    public R detail(@PathVariable("orderSn") String orderSn) {
        OrderDetailVo detailVo =  orderService.detail(orderSn);
        return R.ok().put("data",detailVo);
    }

    @GetMapping("/app/orderList")
    public R OrderList() {
        List<OrderListVo> orderList = orderService.getOrderList();
        return R.ok().put("data", orderList);
    }


}
